
typedef void EventCallback(dynamic argument);

final EventBus eventBus = EventBus();
class EventBus {

  factory EventBus() => _getInstance();
  static EventBus? get instance => _getInstance();
  static EventBus? _instance;
  EventBus._internal();
  static EventBus _getInstance(){
    if(null == _instance){
      _instance = EventBus._internal();
    }
    return _instance!;
  }

  /// key:通知名称/事件名称, value: 对应事件的订阅者队列
  var _eventMap = Map<String, List<EventCallback>?>();

  /// 添加订阅
  void addListener(String eventName, EventCallback callback){
    _eventMap[eventName] ??= <EventCallback>[];
    _eventMap[eventName]!.add(callback);
  }

  /// 移除订阅者
  void removeListener(String eventName, EventCallback callback){
    var list = _eventMap[eventName];
    if(null == list) return;
    list.remove(callback);
  }

  /// 移除所有订阅者
  void removeAllListener(String eventName){
    var list = _eventMap[eventName];
    if(null == list) return;
    list.clear();
    _eventMap[eventName] = null;
  }

  void fireListener(String eventName, {dynamic argument}){
    var list = _eventMap[eventName];
    if(null == list) return;
    int len = list.length - 1;
    // 反向遍历,防止订阅者在回调中移除自身带来的下标错位
    for(var i = len; i > -1; --i){
      list[i](argument);
    }
  }
}
